package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.LinkModel;
import models.UserModel;

import data.LinkData;
import data.UserData;
import debug.LinkDebug;

public class DeleteLinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setContentType("text/html");
		
		UserModel user = (UserModel) request.getAttribute("user");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		long linkId = 0;
		try {
			linkId = Long.parseLong(URLDecoder.decode(path.toLowerCase().replaceAll("/delete-link/", ""),"UTF-8"));
		} catch (Exception e) {
			response.sendRedirect("/home");
		}
		try {
			LinkData linkData = new LinkData();
			LinkModel link = linkData.getLink(linkId);
			
			//Check create link
			if (link == null || user == null || link.getCreator().equalsIgnoreCase(user.getUsername())) {
				response.sendRedirect("/message?txt=not-permission");
				return;
			}
			
			linkData.delete(link);
			LinkDebug.debugWeb(link, response);
		} catch (Exception e) {
			// TODO: handle exception
		}
		response.getWriter().println("Go to <a href=\"/view-category\" >Category </a>");
	}
}
